<template>
  <el-form :model="model" :rules="rules" ref="rechargeform" label-width="100px" v-loading="loading" >
    <el-radio-group v-model="model.changeType">
      <el-radio-button :label="0">充值</el-radio-button>
      <el-radio-button :label="1">扣费</el-radio-button>
    </el-radio-group>
    </br>
    </br>
    <el-form-item :label="model.changeType?'扣费金额':'充值金额'" prop="rechargeValue">
      <el-input v-model="model.rechargeValue"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button round type="primary" @click="onSubmit">{{model.changeType?'确认扣费':'确认充值'}}</el-button>
      <el-button round @click="resrtFrom" >重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { Recharge } from '@/api/user'

export default {
  name: 'recharge',
  data() {
    return {
      loading: false,
      model: {
        rechargeValue: 0,
        userId: 0,
        changeType: 0
      },
      rules: {
        rechargeValue: [
          { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    userId: {
      type: Number,
      default: 0
    }
  },
  watch: {
    userId: {
      immediate: true,
      handler(newVal) {
        this.model.userId = newVal
      }
    }
  },
  methods: {
    onSubmit() {
      var _this = this
      _this.$refs.rechargeform.validate(valid => {
        if (valid) {
          _this.loading = true
          Recharge(_this.model).then(result => {
            _this.$message.success(_this.model.changeType ? '扣费成功' : '充值成功')
            _this.$emit('rechargeSuccessed', result)
            _this.$refs['userform'].resetFields()
            _this.loading = false
          }).catch(response => {
            _this.loading = false
          })
        }
      })
    },
    resrtFrom() {
      this.$refs['userform'].resetFields()
    }
  }
}
</script>
